package com.kxmall.web.controller.vehicle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kxmall.capacity.domain.vo.KxCapacityBoxVo;
import com.kxmall.capacity.domain.vo.KxCapacityVo;
import com.kxmall.common.constant.CacheConstants;
import com.kxmall.common.utils.BeanCopyUtils;
import com.kxmall.common.utils.HttpUtils;
import com.kxmall.common.utils.OrderUtil;
import com.kxmall.common.utils.PageData;
import com.kxmall.order.domain.vo.KxStoreCartVo;
import com.kxmall.vehicle.domain.*;
import com.kxmall.vehicle.domain.vo.*;
import org.apache.commons.lang3.StringUtils;
import com.kxmall.common.utils.redis.RedisUtils;
import com.kxmall.vehicle.mapper.*;
import com.kxmall.web.controller.vehicle.service.IKxAppVehicleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class KxAppVehicleService implements IKxAppVehicleService {

    @Autowired
    private KxVehicleMapper vehicleMapper;
    @Autowired
    private KxVehicleInGoodsMapper vehicleInGoodsMapper;
    @Autowired
    private KxVehicleBoxGoodsMapper vehicleBoxGoodsMapper;
    @Autowired
    private KxVehicleBoxUpGoodsMapper vehicleBoxUpGoodsMapper;
    @Autowired
    private KxVehicleBoxGoodsOrderMapper vehicleBoxGoodsOrderMapper;

    @Value("${capacity.loginURL}")
    private String loginURL = "https://middle.office.xingshentech.com/api/sys/singleLogin?userName=qdqTest&password=qdqTest";

    @Value("${capacity.getURL}")
    private String getURL = "https://middle.office.xingshentech.com/api/task/interface/capacityResourceBoxStatusById?capacityResourceId=";

    public String getVehicleLoginToken(){
        String response = HttpUtils.get(loginURL);
        Map<String,Object> rpMap= JSON.parseObject(response, HashMap.class);
        if ("0".equals(""+rpMap.get("code"))){
            String data = ""+rpMap.get("data");
            Map<String,Object> rpMap1= JSON.parseObject(data, HashMap.class);
            String token = ""+rpMap1.get("token");
            Duration duration = Duration.ofDays(1);
            RedisUtils.setCacheObject(CacheConstants.CAPACITY_LOGIN_TOKEN_KEY, token, duration);
            return token;
        }
        return "";
    }

    @Override
    public KxVehicleVo getVehicleBoxGoodsInfo(String vehicleNo) {
        log.info("getVehicleBoxGoodsInfo vehicleNo={}", vehicleNo);
        KxVehicleVo vehicleVo = vehicleMapper.selectVoOne(
                new LambdaQueryWrapper<KxVehicle>().eq(KxVehicle::getVehicleNo, vehicleNo));
        if (vehicleVo != null) {
            String token = RedisUtils.getCacheObject(CacheConstants.CAPACITY_LOGIN_TOKEN_KEY);
            if(StringUtils.isEmpty(token)){
                token = getVehicleLoginToken();
            }
            Map<String, String> headers = new HashMap<>();
            if(StringUtils.isNotEmpty(token)) {
                headers.put("token", token);
            }
            log.info("getVehicleBoxGoodsInfo vehicleNo={} token={}", vehicleNo, token);
            String response = HttpUtils.get(getURL+vehicleNo,null, headers);
            log.info("getVehicleBoxGoodsInfo vehicleNo={} response={}",vehicleNo, response);
            Map<String,Object> rpMap = JSON.parseObject(response, HashMap.class);
            if ("0".equals(""+rpMap.get("code"))){
                vehicleVo.setIsOnline(1);
                KxCapacityVo kxCapacityVo = JSON.parseObject(""+rpMap.get("data"), KxCapacityVo.class);
                List<KxCapacityBoxVo> kxCapacityBoxVOList = kxCapacityVo.getBoxStatusInfoVOList();
                if(CollectionUtils.isNotEmpty(kxCapacityBoxVOList)){
                    List<KxVehicleBoxGoods> vehicleBoxGoodsList = vehicleBoxGoodsMapper.selectList(
                            new LambdaQueryWrapper<KxVehicleBoxGoods>().eq(KxVehicleBoxGoods::getVehicleNo, vehicleNo)
                    );
                    List<KxVehicleBoxGoodsVo> vehicleBoxGoodsVos = new ArrayList<>();
                    if(CollectionUtils.isNotEmpty(vehicleBoxGoodsList)){
                        for(KxVehicleBoxGoods vehicleBoxGoods : vehicleBoxGoodsList){
                            KxVehicleBoxGoodsVo vehicleBoxGoodsVo = new KxVehicleBoxGoodsVo();
                            BeanCopyUtils.copy(vehicleBoxGoods, vehicleBoxGoodsVo);
                            if((vehicleBoxGoodsVo.getBoxStatus() == 0)
                                &&(vehicleBoxGoodsVo.getBoxStates() == 1)
                                &&(vehicleBoxGoodsVo.getUpGoodsId() != null)
                                &&(vehicleBoxGoodsVo.getUpGoodsId() != 0)) {
                                KxVehicleBoxUpGoodsVo vehicleBoxUpGoodsVo = vehicleBoxUpGoodsMapper.selectVoById(vehicleBoxGoodsVo.getUpGoodsId());
                                if(vehicleBoxGoodsVo != null) {
                                    vehicleBoxGoodsVo.setGoodsNumbers(vehicleBoxUpGoodsVo.getGoodsNumbers());
                                    vehicleBoxGoodsVo.setSalesStatus(vehicleBoxUpGoodsVo.getSalesStatus());
                                    vehicleBoxGoodsVo.setUpPerson(vehicleBoxUpGoodsVo.getUpPerson());
                                    vehicleBoxGoodsVo.setUpTime(vehicleBoxUpGoodsVo.getUpTime());
                                    vehicleBoxGoodsVo.setUpDay(vehicleBoxUpGoodsVo.getUpDay());
                                    vehicleBoxGoodsVo.setRemarks(vehicleBoxUpGoodsVo.getRemarks());
                                    vehicleBoxGoodsVo.setCount(vehicleBoxUpGoodsVo.getCount());
                                    vehicleBoxGoodsVo.setPrice(vehicleBoxUpGoodsVo.getPrice());
                                    vehicleBoxGoodsVo.setAmount(vehicleBoxUpGoodsVo.getAmount());
                                    KxVehicleInGoods vehicleInGoods = vehicleInGoodsMapper.selectById(vehicleBoxGoodsVo.getInGoodsId());
                                    if(vehicleInGoods != null) {
                                        vehicleBoxGoodsVo.setInVehicleOrder(vehicleInGoods.getInVehicleOrder());
                                        vehicleBoxGoodsVo.setInVehicleCount(vehicleInGoods.getInVehicleCount());
                                        vehicleBoxGoodsVo.setProductId(vehicleInGoods.getProductId());
                                        vehicleBoxGoodsVo.setProductName(vehicleInGoods.getProductName());
                                        vehicleBoxGoodsVo.setProductAttrId(vehicleInGoods.getProductAttrId());
                                        vehicleBoxGoodsVo.setProductAttrName(vehicleInGoods.getProductAttrName());
                                        vehicleBoxGoodsVo.setCategoryId(vehicleInGoods.getCategoryId());
                                        vehicleBoxGoodsVo.setCategoryName(vehicleInGoods.getCategoryName());
                                        vehicleBoxGoodsVo.setOrPrice(vehicleInGoods.getOrPrice());
                                        //vehicleBoxGoodsVo.setBarCode(vehicleInGoods.getBarCode());
                                        vehicleBoxGoodsVo.setStock(vehicleInGoods.getStock());
                                        vehicleBoxGoodsVo.setSalesStatus(vehicleInGoods.getSalesStatus());
                                    }
                                }
                            }
                            for(KxCapacityBoxVo capacityBoxVo : kxCapacityBoxVOList){
                                if((vehicleBoxGoodsVo.getBoxIndex().intValue() == capacityBoxVo.getBoxIndex().intValue())
                                        &&(vehicleBoxGoodsVo.getBoxStatus().intValue() != capacityBoxVo.getBoxStatus().intValue())){
                                    vehicleBoxGoodsVo.setBoxStatus(capacityBoxVo.getBoxStatus());
                                    vehicleBoxGoodsMapper.updateVehicleBoxStatus(vehicleBoxGoodsVo.getId(), capacityBoxVo.getBoxStatus());
                                }
                            }
                            vehicleBoxGoodsVos.add(vehicleBoxGoodsVo);
                        }
                    }
                    vehicleVo.setVehicleBoxGoodsVos(vehicleBoxGoodsVos);
                }
                log.info("getVehicleBoxGoodsInfo vehicleVo={}", JSONObject.toJSONString(vehicleVo));
                return vehicleVo;
            }

            if ("401".equals(""+rpMap.get("code"))){
                getVehicleLoginToken();
                vehicleVo = getVehicleBoxGoodsInfo(vehicleNo);
                log.info("getVehicleBoxGoodsInfo vehicleVo={}", JSONObject.toJSONString(vehicleVo));
                return vehicleVo;
            }
        }

        vehicleVo = new KxVehicleVo();
        vehicleVo.setIsOnline(0);
        vehicleVo.setBoxNum(24);
        List<KxVehicleBoxGoodsVo> vehicleBoxGoodsVos = new ArrayList<>();
        for(int i=1; i<25; i++){
            KxVehicleBoxGoodsVo kxCapacityBoxVo = new KxVehicleBoxGoodsVo();
            kxCapacityBoxVo.setBoxIndex(i);
            kxCapacityBoxVo.setBoxStatus(-1);
            kxCapacityBoxVo.setBoxStates(0);
            vehicleBoxGoodsVos.add(kxCapacityBoxVo);
        }
        vehicleVo.setVehicleBoxGoodsVos(vehicleBoxGoodsVos);
        //log.info("getVehicleBoxGoodsInfo vehicleVo={}", JSONObject.toJSONString(vehicleVo));
        return vehicleVo;
    }

    @Override
    public PageData createVehicleBoxGoodsOrder(Long userId, String vehicleNo, Integer boxIndex) {
        PageData ack = new PageData();
        KxVehicleBoxGoods vehicleBoxGoods = vehicleBoxGoodsMapper.selectOne(
                new LambdaQueryWrapper<KxVehicleBoxGoods>()
                        .eq(KxVehicleBoxGoods::getVehicleNo, vehicleNo)
                        .eq(KxVehicleBoxGoods::getBoxIndex,boxIndex));
        if((vehicleBoxGoods.getBoxStatus() == 0)
                &&(vehicleBoxGoods.getBoxStates() == 1)){
            String orderNo = OrderUtil.getOrderIdByUUId();
            KxVehicleBoxGoodsOrder vehicleBoxGoodsOrder = new KxVehicleBoxGoodsOrder();
            vehicleBoxGoodsOrder.setUserId(userId);
            vehicleBoxGoodsOrder.setOrderNo(orderNo);
            vehicleBoxGoodsOrder.setOrderStatus(0);
            vehicleBoxGoodsOrder.setVehicleId(vehicleBoxGoods.getVehicleId());
            vehicleBoxGoodsOrder.setVehicleNo(vehicleBoxGoods.getVehicleNo());
            vehicleBoxGoodsOrder.setVehicleName(vehicleBoxGoods.getVehicleName());
            vehicleBoxGoodsOrder.setBoxIndex(vehicleBoxGoods.getBoxIndex());
            vehicleBoxGoodsOrder.setInGoodsId(vehicleBoxGoods.getInGoodsId());
            vehicleBoxGoodsOrder.setUpGoodsId(vehicleBoxGoods.getUpGoodsId());
            KxVehicleBoxUpGoods vehicleBoxUpGoods = vehicleBoxUpGoodsMapper.selectById(vehicleBoxGoods.getUpGoodsId());
            vehicleBoxGoodsOrder.setPrice(vehicleBoxUpGoods.getPrice());
            vehicleBoxGoodsOrder.setCount(vehicleBoxUpGoods.getCount());
            vehicleBoxGoodsOrder.setAmount(vehicleBoxUpGoods.getAmount());
            vehicleBoxGoodsOrder.setOrderStatus(0);
            int ret = vehicleBoxGoodsOrderMapper.insert(vehicleBoxGoodsOrder);
            if(ret > 0) {
                ack.put("vehicleNo", vehicleNo);
                ack.put("boxIndex", boxIndex);
                ack.put("userId", userId);
                ack.put("orderNo", orderNo);
                ack.put("orderStatus", 0);
                ack.put("price", vehicleBoxUpGoods.getPrice());
                ack.put("count", vehicleBoxUpGoods.getCount());
                ack.put("amount", vehicleBoxUpGoods.getAmount());
                return ack;
            }
        }
        ack.put("userId", userId);
        ack.put("vehicleNo",vehicleNo);
        ack.put("boxIndex",boxIndex);
        ack.put("orderNo","");
        ack.put("orderStatus",0);
        ack.put("count", 0);
        ack.put("price", 0.00);
        ack.put("amount",0.00);
        return ack;
    }

    @Override
    public List<KxUserGoodsOrderVo> getUserGoodsOrderList(Long userId) {
        List<KxUserGoodsOrderVo> userGoodsOrderVos = new ArrayList<>();
        List<KxVehicleBoxGoodsOrder> vehicleBoxGoodsOrderList = vehicleBoxGoodsOrderMapper.selectList(
                new LambdaQueryWrapper<KxVehicleBoxGoodsOrder>().eq(KxVehicleBoxGoodsOrder::getUserId, userId));
        if(!vehicleBoxGoodsOrderList.isEmpty()){
            for(KxVehicleBoxGoodsOrder vehicleBoxGoodsOrder : vehicleBoxGoodsOrderList){
                KxUserGoodsOrderVo userGoodsOrderVo = new KxUserGoodsOrderVo();
                userGoodsOrderVo.setId(vehicleBoxGoodsOrder.getId());
                userGoodsOrderVo.setUserId(vehicleBoxGoodsOrder.getUserId());
                userGoodsOrderVo.setVehicleId(vehicleBoxGoodsOrder.getVehicleId());
                userGoodsOrderVo.setVehicleNo(vehicleBoxGoodsOrder.getVehicleNo());
                userGoodsOrderVo.setVehicleName(vehicleBoxGoodsOrder.getVehicleName());
                userGoodsOrderVo.setOrderNo(vehicleBoxGoodsOrder.getOrderNo());
                userGoodsOrderVo.setOrderStatus(vehicleBoxGoodsOrder.getOrderStatus());
                userGoodsOrderVo.setCount(vehicleBoxGoodsOrder.getCount());
                userGoodsOrderVo.setPrice(vehicleBoxGoodsOrder.getPrice());
                userGoodsOrderVo.setAmount(vehicleBoxGoodsOrder.getAmount());
                KxVehicleInGoods vehicleInGoods = vehicleInGoodsMapper.selectById(vehicleBoxGoodsOrder.getInGoodsId());
                if(vehicleInGoods != null) {
                    //userGoodsOrderVo.setBarCode(vehicleInGoods.getBarCode());
                    userGoodsOrderVo.setProductId(vehicleInGoods.getProductId());
                    userGoodsOrderVo.setProductName(vehicleInGoods.getProductName());
                    userGoodsOrderVo.setProductAttrId(vehicleInGoods.getProductAttrId());
                    userGoodsOrderVo.setProductAttrName(vehicleInGoods.getProductAttrName());
                    userGoodsOrderVo.setCategoryId(vehicleInGoods.getCategoryId());
                    userGoodsOrderVo.setCategoryName(vehicleInGoods.getCategoryName());
                }
            }
        }
        return userGoodsOrderVos;
    }

}
